package com.itheima.reggie.common;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author mff
 * @date 2022/6/8 10:36
 * @mood happy
 */
@RestControllerAdvice  //Rest可以将返回的数据转为JSON格式放回给前端，若不使用@RestControllerAdvice，而使用@ControllerAdvice，则必须在类中的方法
@Component   //表示是一个bean，加入到SpringMVC容器中
public class GlobalExceptionHandler {
    //处理具体的异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
//    @RequestBody
    public R<String> handlerException(SQLIntegrityConstraintViolationException e) {
//        打印异常信息
        e.printStackTrace();
        e.equals("Duplicate entry");
        if (e instanceof SQLIntegrityConstraintViolationException){
            String message = e.getMessage();
            String[] s = message.split(" ");
            String msg = s[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
}
